﻿using System;
using System.Web.SessionState;
using Jayrock.JsonRpc;
using Jayrock.JsonRpc.Web;

namespace N2.Web.Services
{
	using Engine;
	
	public class Persister : JsonRpcHandler, IRequiresSessionState
	{
		IEngine Engine = N2.Context.Current;
		
		[JsonRpcMethod("get", Idempotent = true)]
		[JsonRpcHelp("Get a ContentItem by id")]
		public ContentItem Get(int id)
		{
			var _item = this.Engine.Persister.Get(id);
			EnsureIsAuthorizedFor(_item);
			return _item;
		}

		[JsonRpcMethod("put", Idempotent = false)]
		public object Save(ContentItem item)
		{
			EnsureIsAuthorizedFor(item);
			this.Engine.Persister.Save(item);
			return new { __deferred = new { item.ID } };
		}

		[JsonRpcMethod("delete", Idempotent = false)]
		public void Delete(int id)
		{
			var _item = this.Get(id);

			EnsureIsAuthorizedFor(_item);

			this.Engine.Persister.Delete(_item);
		}

		void EnsureIsAuthorizedFor(ContentItem item)
		{
			var _user = this.Context.User;

			if (!Engine.SecurityManager.IsAdmin(_user)
					&& !item.IsAuthorized(_user)) {
				throw new InvalidOperationException("Not authorized to perform this opration");
			}
		}
	}
}
